package com.neuedu.controller;

import com.alibaba.fastjson2.JSON;
import com.neuedu.model.Stock;
import com.neuedu.service.ProductServiceFeign;
import com.neuedu.service.StockService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.persistence.Entity;


@Slf4j
@RestController
@Component
@Entity
@Controller
public class StockController {

    @Autowired
    private StockService stockService;

    @Autowired
    private ProductServiceFeign productServiceFeign;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @RequestMapping("/stock/{sid}")
    @GetMapping
    public Stock getStockById(@PathVariable("sid") Integer sid) {
        log.info("查看{}库存信息", sid);
        Stock stock = stockService.queryStockById(sid);
        rocketMQTemplate.convertAndSend("stock-topic", stock);
        log.info("库存信息查询成功，内容为：{}", JSON.toJSONString(stock));
        return stock;
    }

    @RequestMapping("/stock/api1/demo1")
    public String api1Demo1() {
        return "api1-demo1";
    }

    @RequestMapping("/stock/api1/demo2")
    public String api1Demo2() {
        return "api1-demo2";
    }

    @RequestMapping("/stock/api2/demo1")
    public String api2Demo1() {
        return "api2-demo1";
    }

    @RequestMapping("/stock/api2/demo2")
    public String api2Demo2() {
        return "api2-demo2";
    }

    //商品信息管理-添加功能
    @PostMapping("/stock/add")
    public String addStock(@RequestBody Stock stock) {
        stockService.addStock(stock);
        return "库存添加成功";
    }

    // 减少库存
    @PostMapping("/stock/reduceStock/{sid}/{quantity}")
    public String reduceStock(@PathVariable("sid") Integer sid,
                              @PathVariable("quantity") Integer quantity) {
        boolean result = stockService.reduceStock(sid, quantity);
        if (result) {
            return "库存减少成功";
        } else {
            return "库存减少失败，库存不足";
        }
    }

    // 增加库存
    @PostMapping("/stock/increaseStock")
    public String increaseStock(@RequestBody Stock stock) {
        stockService.addStock(stock);
        return "商品评价添加成功";
    }
}